package com.modules.asset.service.impl;

import com.modules.asset.model.dto.UserCreateRequest;
import com.modules.asset.model.dto.UserResponse;
import com.modules.asset.model.dto.UserUpdateRequest;
import com.modules.asset.model.entity.User;
import com.modules.asset.mapper.UserMapper;
import com.modules.asset.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.modules.asset.common.ErrorCode;
import com.modules.asset.common.ThrowUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * User 服务实现。
 * 自动生成时间：2025-10-27 16:44:22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public UserResponse create(UserCreateRequest request) {
        User entity = new User();
        BeanUtils.copyProperties(request, entity);
        boolean saved = save(entity);
        ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR, "保存User失败");
        return toResponse(entity);
    }

    @Override
    public UserResponse update(Long id, UserUpdateRequest request) {
        User entity = getById(id);
        ThrowUtils.throwIf(entity == null, ErrorCode.NOT_FOUND_ERROR, "User不存在");
        BeanUtils.copyProperties(request, entity);
        boolean updated = updateById(entity);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "更新User失败");
        return toResponse(entity);
    }

    @Override
    public void delete(Long id) {
        boolean removed = removeById(id);
        ThrowUtils.throwIf(!removed, ErrorCode.NOT_FOUND_ERROR, "User不存在");
    }

    @Override
    public UserResponse findById(Long id) {
        User entity = getById(id);
        ThrowUtils.throwIf(entity == null, ErrorCode.NOT_FOUND_ERROR, "User不存在");
        return toResponse(entity);
    }

    @Override
    public List<UserResponse> listAll() {
        return list().stream().map(this::toResponse).collect(Collectors.toList());
    }

    private UserResponse toResponse(User entity) {
        if (entity == null) {
            return null;
        }
        UserResponse response = new UserResponse();
        BeanUtils.copyProperties(entity, response);
        return response;
    }
}
